package com.adminpanel.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.adminpanel.modelbean.UploadBean;
import com.adminpanel.modelbean.UserBean;
import com.adminpanel.modelbean.UserfileBean;
import com.adminpanel.service.UploadImpl;
import com.adminpanel.service.UserfileServices;
import com.adminpanel.util.Util;


@RequestMapping("/uploadfiles")
@Controller
@SessionAttributes("loginuser")
public class UploadController {
	
	
	@Resource(name = "uploadImpl")
	private UploadImpl uploadImpl;
	
	@Resource(name = "userfileServices")
	private UserfileServices userfileServices;

	UserfileBean userfileBean = new UserfileBean();
	@RequestMapping(method = RequestMethod.GET)
	public String getUploadForm(Model model) {
		model.addAttribute("uploadBean", new UploadBean());
		model.addAttribute("sessionId", RequestContextHolder.currentRequestAttributes().getSessionId());
		return "userfile";
	}
	
	

	@RequestMapping(method = RequestMethod.POST)
	public String uploadcreate(@ModelAttribute("loginuser") UserBean userBean,UploadBean uploadBean, BindingResult result, HttpServletRequest request) {
        
        if (result.hasErrors()) {
            for (ObjectError error : result.getAllErrors()) {
                System.err.println("Error in uploading: " + error.getCode()
                        + " - " + error.getDefaultMessage());
            }
            return "userfile";
        }
       
       
        boolean success = uploadImpl.upload(uploadBean,userfileBean, userBean.getId(),new Util().getDate());
        
        userfileServices.addUploadData(userBean.getId(),
        								uploadBean.getFiledata().getOriginalFilename(),
        								userfileBean.getSave_path(),
        								new Util().formatSize(uploadBean.getFiledata().getSize()),
        								new Util().getDate());
        
        if (success){
            return "success";
        }
        else{
            return "userfile";
        }
    }
	

}
